const {
  aiCreationApi
} = require('../api/index')
const {
  Base64
} = require('js-base64')
const Crypto = require('crypto-js')

const uploadFile = async (data) => {

  const params = await aiCreationApi.getSts({
    stsType: 1
  })
  // console.log('p凭证', params);
  const {
    accessKeyId,
    accessKeySecret,
    securityToken,
    region,
    bucket,
  } = params;


  const date = new Date();
  date.setHours(date.getHours() + 1);
  const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
      // 限制上传大小。
      ["content-length-range", 0, 1024 * 1024 * 1024],
    ],
  };

  const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
  const signature = Crypto.enc.Base64.stringify(Crypto.HmacSHA1(policy, accessKeySecret));
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      // url: `https://${bucket}.${region}.aliyuncs.com`,
      url: data.host,
      filePath: data.filePath,
      name: 'file',
      formData: {
        key: data.key,
        policy,
        region,
        OSSAccessKeyId: accessKeyId,
        signature,
        'x-oss-security-token': securityToken // 使用STS签名时必传。
      },
      success(res) {
        resolve(res);
      },
      fail(err) {
        console.log('上传失败', err);
        reject(err);
      }
    })
  })

}
module.exports = {
  uploadFile
}